package cn.house.rent.controller;

import cn.house.rent.entity.User;
import cn.house.rent.service.OrderService;
import cn.house.rent.utils.AlipayConfig;
import cn.house.rent.utils.Result;
import cn.house.rent.vo.OrderVo;
import cn.house.rent.vo.TenantHomeVo;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    private static OrderVo order;

    //我的家取消  要删除租客和房东订单表中相应的订单  并且将对应的房子状态该为出租 7
    @RequestMapping("canceltenant")
    @ResponseBody
    public Object cancelTenant(TenantHomeVo tenantHomeVo){
        Result result = orderService.cancelTenant(tenantHomeVo);
        return result;
    }

    //租客个人订单模块查询和搜索查询
    @RequestMapping("tenantorder")
    @ResponseBody
    public Object tenantOrder(OrderVo orderVo, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Result result = orderService.tenantOrder(user, orderVo);
        return result;
    }

    //租客个人订单模块  取消功能
    @RequestMapping("canceltenorder")
    @ResponseBody
    public Object canceltenorder(TenantHomeVo tenantHomeVo){
        Result result = orderService.cancelTenOrder(tenantHomeVo);
        return result;
    }

    //租客个人订单模块  删除功能
    @RequestMapping("deltenorder")
    @ResponseBody
    public Object deltenorder(TenantHomeVo tenantHomeVo){
        Result result = orderService.delTenOrder(tenantHomeVo);
        return result;
    }

    //房东个人订单模块查询和搜索查询
    @RequestMapping("landorder")
    @ResponseBody
    public Object landOrder(OrderVo orderVo, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Result result = orderService.landOrder(user, orderVo);
        return result;
    }

    //房东  个人订单  同意功能
    @RequestMapping("passorder")
    @ResponseBody
    public Object passOrder(OrderVo orderVo){
       Result result = orderService.passOrder(orderVo);
       return result;
    }

    //房东  个人订单  驳回功能
    @RequestMapping("rejectorder")
    @ResponseBody
    public Object rejectOrder(OrderVo orderVo){
        Result result = orderService.rejectOrder(orderVo);
        return result;
    }

    //房东  个人订单  删除功能
    @RequestMapping("dellandorder")
    @ResponseBody
    public Object delLandOrder(OrderVo orderVo){
        Result result = orderService.delLandOrder(orderVo);
        return result;
    }

    // 用户提交租房订单
    @RequestMapping("addOrder")
    @ResponseBody
    public Object addOrder(OrderVo orderVo) {
        return orderService.addOrder(orderVo);
    }

    @RequestMapping("alipay")
    public void payController(OrderVo orderVo, HttpServletResponse response){
        OrderController.order = orderVo;
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        //商户订单号
        String out_trade_no = orderVo.getHouseOrderId();
        // 付款金额
        String total_amount = String.valueOf(orderVo.getOrderPrice());
        // 订单名称
        String subject = orderVo.getHouseName();
        // 商品描述
        String body = "";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\"" + total_amount
                + "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=" + AlipayConfig.charset);
        try {
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("returnUrl")
    public String returnUrlMethod(HttpServletRequest request, HttpSession session) throws AlipayApiException, UnsupportedEncodingException {
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //验证签名（支付宝公钥）
        boolean signVerified = AlipaySignature.rsaCheckV2(params, AlipayConfig.alipay_public_key, AlipayConfig.charset,AlipayConfig.sign_type); // 调用SDK验证签名
        //验证签名通过
//        if(signVerified){
//
//        }else{
//
//        }
        orderService.addOrder(order);
        order = null;
        return "redirect:/jsp/main.jsp";
    }

}
